﻿using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Logging;
using MyCommon.HttpContextUser;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.Json;
using System.Threading.Tasks;

namespace MyCommon.Caches
{
    public class Caching(IDistributedCache cache) :ICaching
    {
        public IDistributedCache Cache => cache;

        public bool Exists(string cacheKey)
        {
            var res = cache.Get(cacheKey);
            return res != null;
        }

        public object Get(Type type, string cacheKey)
        {
            var res = cache.Get(cacheKey);
            return res == null ? default : JsonConvert.DeserializeObject(Encoding.UTF8.GetString(res), type);
        }

        public void Set<T>(string cacheKey, T value, TimeSpan? expire = null)
        {
            var b = GetBytes<T>(value);//Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(value));
            cache.Set(cacheKey, b,
           expire == null
               ? new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = TimeSpan.FromHours(6) }
               : new DistributedCacheEntryOptions() { AbsoluteExpirationRelativeToNow = expire });
        }

        private byte[] GetBytes<T>(T source)
        {
             return Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(source));
           // return Encoding.UTF8.GetBytes(System.Text.Json.JsonSerializer.Serialize(source));
        }
    }
}
